@file:OptIn(DelicateCoroutinesApi::class)

package com.kira.solo.schedule.domain

import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 定时任务启动器
 * @packageName com.kira.solo.schedule.domain
 * @date 2024/1/26 10:31
 * @author zhanglei
 */
@Singleton
class ScheduleStarterUseCase @Inject constructor(
    private val service: AlarmScheduleService,
    private val scheduleTasksService: ScheduleTasksService,
) {
    private var job: Job? = null
    operator fun invoke() {
        job?.cancel()
        job = GlobalScope.launch {
            scheduleTasksService.scheduledTasks
                .distinctUntilChanged()
                .collectLatest {
                    service.startAlarm(it.toList())
                }
        }
    }
}